package com.ruoyi.wapp.config.interceptor;

import com.ruoyi.common.constant.CacheKeyConstants;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.wapp.util.MyConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.concurrent.TimeUnit;

import static com.ruoyi.wapp.util.MyConstants.*;


public class TokenInterceptor extends HandlerInterceptorAdapter {
	@Resource
	private RedisTemplate redisTemplate;
	@Override
	public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader(CONFIG.TOKEN_HEAD_NAME);
		if(!StringUtils.isBlank(token)) {
			String tokenCacheKey = CacheKeyConstants.getTempletString(CacheKeyConstants.TOKEN_TPL, token);
			redisTemplate.expire(tokenCacheKey, CONFIG.SESSION_TIMEOUT, TimeUnit.SECONDS);
			Object user = redisTemplate.opsForValue().get(CacheKeyConstants.getTempletString(CacheKeyConstants.TOKEN_TPL, token));
			if(user == null) {
				throw new BusinessException(ResultConstants.EX9112,MessageUtils.message("user.notfound"));
			}
			request.setAttribute(CONFIG.RUQUEST_MEMBER_NAME, user);
		}
		return true;
	}

	
}
